﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;

namespace ProtocolConversion_WINCE
{
    /// <summary>
    /// 向上位机发送数据类
    /// </summary>
    class Communication
    {
        byte[] messageDate = new byte[1024];//接收缓存的数据
        private static SerialPort comport = new SerialPort();
        #region
        private short power;
        public short Power
        {
            get { return power; }
            set { power = value; }
        }
        private short temperture;
        public short Temperture
        {
            get { return temperture; }
            set { temperture = value; }
        }
        private short netWorkState;
        public short NetWorkState
        {
            get { return netWorkState; }
            set { netWorkState = value; }
        }
        private long memorySize;
        public long MemorySize
        {
            get { return memorySize; }
            set { memorySize = value; }
        }
        private short gpsState;
        public short GpsState
        {
            get { return gpsState; }
            set { gpsState = value; }
        }
        private short unUsed;
        public short UnUsed
        {
            get { return unUsed; }
            set { unUsed = value; }
        }
        #endregion

        /// <summary>
        /// 初始化
        /// </summary>
        public static bool InitPort()
        {
            if (comport.IsOpen)
                comport.Close();
            comport.BaudRate = 9600;
            comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "one", true);
            //comport.Parity = (Parity)Enum.Parse(typeof(Parity), null, true);
            comport.PortName = "COM3";
            try
            {
                comport.Open();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
            
        }
        public static void SendMessage(byte[] messageDate, int length)
        {
            if (Converter.BytesToUInt32(messageDate, 0) != 0xbf139774 && !comport.IsOpen) return;
            try
            {
                // Send the binary data out the port
                comport.Write(messageDate, 0, length);
            }
            catch (FormatException)
            {
                // MessageBox.Show("send error.");
            }
        }
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }
        public static void ClosePort()
        {
            if (comport.IsOpen)
            {
                comport.Close();
            }
        }
    }
}
